<?php
/**
 * @link http://www.open-open.com/lib/view/open1355830836135.html
 */

namespace App\Console\Commands;

use App\App\Services\VoteService;
use App\Contracts\Repositories\ActivityModelRepository;
use App\Contracts\Repositories\ActivityRepository;
use App\Models\ActivityModel\ActivityModel;
use Carbon\Carbon;
use Illuminate\Console\Command;

class Cache extends Command
{
    /**
     * @var VoteService
     */
    private $voteService;

    /**
     * @var ActivityRepository
     */
    private $activities;

    /**
     * @var ActivityModelRepository
     */
    private $activityModels;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cache';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '把数据库中的数据写入Redis缓存。';


    public function __construct(VoteService $voteService, ActivityRepository $activities, ActivityModelRepository $activityModels)
    {
        parent::__construct();
        $this->voteService = $voteService;
        $this->activities = $activities;
        $this->activityModels = $activityModels;
    }

    public function handle()
    {
        echo "读取投票数据到缓存" . PHP_EOL;
        $activityModel = $this->activityModels->findByRule(ActivityModel::ACTIVITY_MODEL_VOTE);
        if (!$activityModel) {
            echo "完成" . PHP_EOL;
            exit;
        }
        $activities = $this->activities->findRunningModel($activityModel->id);
        if ($activities->count()) {
            foreach ($activities as $activity) {
                echo 'Running activity:' . $activity->id . PHP_EOL;
                if (!$this->voteService->bootstraped($activity->id)) {
                    $this->voteService->bootstrap($activity->id);
                    echo 'Set activity cache:' . $activity->id . PHP_EOL;
                }
            }
        }
        echo Carbon::now()->format('Y-m-d H:i:s') . PHP_EOL;
        echo "完成" . PHP_EOL;
    }
}
